package com.jrx.anytxn.param.job.bactchBillCompare.config;

import com.jrx.anytxn.param.config.AnytxnBatchProperties;
import com.jrx.anytxn.param.config.BillCompareConfig;
import com.jrx.anytxn.param.config.PathFileConfig;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.entity.TlBillTransCompareDetail;
import com.jrx.anytxn.param.entity.TlThirdBillDetail;
import com.jrx.anytxn.param.job.bactchBillCompare.step.BillDetailUnmatchedWriter;
import com.jrx.anytxn.param.job.bactchBillCompare.step.ThirdDetailUnmatchedProcessor;
import com.jrx.anytxn.param.job.bactchBillCompare.step.WexinBillUnmatchedJobListener;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.batch.MyBatisCursorItemReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.support.SynchronizedItemStreamReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SimpleAsyncTaskExecutor;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 核心对账-将未能匹配到txn交易记录的账务明细写入对账明细表job
 *
 * @author : zcc
 * 2020/11/26
 */
@Configuration
@EnableConfigurationProperties(PathFileConfig.class)
public class WexinBillUnmatchedConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(WexinBillUnmatchedConfiguration.class);

    @Resource(name = "paramSqlSessionFactory")
    SqlSessionFactory sqlSessionFactory;

    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    public StepBuilderFactory stepBuilderFactory;

    @Autowired
    private AnytxnBatchProperties anytxnBatchProperties;

    @Autowired
    private ThirdDetailUnmatchedProcessor thirdDetailUnmatchedProcessor;

    @Autowired
    private BillDetailUnmatchedWriter billDetailUnmatchedWriter;

    @Autowired
    private WexinBillUnmatchedJobListener wexinBillUnmatchedJobListener;

    @Autowired
    private BillCompareConfig billCompareConfig;

    @Bean
    public Job wexinBillUnmatchedJob() {
        return jobBuilderFactory.get("wexinBillUnmatchedJob")
                .incrementer(new RunIdIncrementer())
                .listener(wexinBillUnmatchedJobListener)
                .start(wexinBillUnmatchedStep()) //将未能匹配到txn交易记录的账务明细写入对账明细表
                .build();
    }

    @Bean
    public Step wexinBillUnmatchedStep(){
        return stepBuilderFactory.get("wexinBillUnmatchedStep")
                .<TlThirdBillDetail, TlBillTransCompareDetail>chunk(anytxnBatchProperties.getBatchBillCompareConfiguration().getChunkLimit())
                //表示一批处理100
                // 条记录，数据是逐条发送给processor处理的，处理100条记录后，统一返回给writer进行保存处理
                .reader(wexinBillUnmatchedReader(null, null))
                .processor(thirdDetailUnmatchedProcessor)
                .writer(billDetailUnmatchedWriter)
                .taskExecutor(new SimpleAsyncTaskExecutor())
                .throttleLimit(anytxnBatchProperties.getBatchBillCompareConfiguration().getThrottleLimit())//多线程*/
                .build();
    }

    @Bean
    @StepScope
    public SynchronizedItemStreamReader<TlThirdBillDetail> wexinBillUnmatchedReader(@Value("#{jobExecutionContext['PR_ORG_TODAY']}") Date today,
                                                                                    @Value("#{jobExecutionContext['PR_ORG_TENANT']}") String tenantId) {
        MyBatisCursorItemReader<TlThirdBillDetail> cursorItemReader = new MyBatisCursorItemReader<>();
        cursorItemReader.setSaveState(false);
        cursorItemReader.setSqlSessionFactory(sqlSessionFactory);
        cursorItemReader.setQueryId("com.jrx.anytxn.param.mapper.ext.ExtTlThirdBillDetailMapper.selectForBillComparing");
        Map<String, Object> map = new HashMap<>();
        map.put("tenantId", tenantId);
        map.put("businessDate", today);
        map.put("compareFlag", Constant.COMPARE_FLAG_0);
        map.put("thirdChannel", billCompareConfig.getThirdChannel());
        cursorItemReader.setParameterValues(map);

        SynchronizedItemStreamReader<TlThirdBillDetail> synchronizedItemStreamReader = new SynchronizedItemStreamReader<>();
        synchronizedItemStreamReader.setDelegate(cursorItemReader);
        return synchronizedItemStreamReader;
    }

}